package dmmm.components;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

public class MEM extends LogicalComponent {
	private ArrayList<Integer> memory;
	private Pin read;
	private Pin write;
	private int size;

	public MEM(int size) {
		super(2, 1, true);
		out[0].setIsInt();
		//samo je jedan izlaz koji se postavlja da je INT
		
		this.size = size;
		memory = new ArrayList<Integer>(size);
		for (int i = 0; i < size; i++)
			memory.add(0);
		addSequentialComponent(this);
	}

	public void func() {
		if (write.getBoolVal()) {
			memory.set(in[0].getIntVal(), in[1].getIntVal());
		}

		if (read.getBoolVal()) {
			out[0].setIntVal(memory.get(in[0].getIntVal()),false);
		}
	}
	
	// Dodato: Djole
	public void clear() {
		for (int i = 0; i < size; i++)
			memory.set(i,0);
	}

	public int getSize() {
		return size;
	}

	public void setRead(Pin read) {
		this.read = read;
		read.addChild(this);
	}

	public void setWrite(Pin write) {
		this.write = write;
		write.addChild(this);
	}
	public void set(int adress,int data){
		memory.set(adress, data);
	}
	
	public void setMemory(ArrayList<Integer> memory){
		this.memory=memory;
		this.size=memory.size();
	}
	
	
	public void write(int address, int data){
		memory = new ArrayList<Integer>(memory);
		memory.set(address, data);
		if (read.getBoolVal() && (in[0].getIntVal() == address)) {
			out[0].setIntVal(memory.get(address), false);
		}
	}
	
	
	public int read(int adress){
		return memory.get(adress);
	}
	public void init(){
		if(initMemory)
			for (int i = 0; i < size; i++)
				memory.set(i,0);
	}
	//CUVANJE STANJA ZBOG VRACANJA UNAZAD
	// radi cuvanja - exp
	public State getState() {
		return new State(memory, out[0].getIntVal());
	}
	
	@SuppressWarnings("unchecked")
	public void restoreState(State state) {
		memory = (ArrayList<Integer>)state.innerState;
		out[0].setIntVal((Integer)state.outPin, false);
	}
	//ZA CUVANJE STANJA ZA UPIS U FAJL
	@SuppressWarnings("unchecked")
	public void writeState(State state, PrintWriter writer) {
		ArrayList<Integer> mem = (ArrayList<Integer>) state.innerState;
		for(int i = 0; i < mem.size(); i++) {
			if(mem.get(i)!=0) {
				writer.println(i+": "+mem.get(i));
			}
		}
		writer.println((Integer)state.outPin);
	}
	
	public void loadState(BufferedReader reader) {
		memory = new ArrayList<Integer>(size);
		for (int i = 0; i < size; i++) {
			memory.add(0);
		}
		try {
			String memLoc = reader.readLine();
			while(memLoc.contains(":")) {
				String[] tokens = memLoc.split(":");
				write(Integer.parseInt(tokens[0]), Integer.parseInt(tokens[1].trim()));
				memLoc = reader.readLine();
			}
			out[0].setIntVal(Integer.parseInt(memLoc), false);
		} catch (IOException e) {
			System.out.println("Error reading save file!");
		}
	}

}
